package com.renting.common.security;

import com.renting.common.announce.LoginRequired;
import com.renting.common.config.HttpStatusConstant;
import com.renting.common.entity.Result;
import org.apache.ibatis.plugin.Intercepts;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;

/**
 * 自定义的一个登录拦截器
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            LoginRequired loginRequired = findAnnotation((HandlerMethod) handler, LoginRequired.class);
            //没有声明需要权限,或者声明不验证权限
            if (loginRequired == null) {
                return true;
            } else {
                String token = request.getHeader("token");//得到token
                if (StringUtils.isEmpty(token)) {
                    token = request.getParameter("token");
                }
                //在这里实现自己的权限验证逻辑
                if (!StringUtils.isEmpty(token)) {//如果验证成功返回true（这里直接写false来模拟验证失败的处理）
                    return true;
                } else {//如果验证失败


                    response.getWriter().write(new Result(HttpStatusConstant.REQUIRED_LOGIN).toJSONString());
                    return false;
                }
            }
        } else {
            return true;
        }
    }

    private <T extends Annotation> T findAnnotation(HandlerMethod handler, Class<T> annotationType) {
        T annotation = handler.getBeanType().getAnnotation(annotationType);
        if (annotation != null) return annotation;
        return handler.getMethodAnnotation(annotationType);
    }
}
